package com.aurora_manito.xiaomi.Controller;


import cn.dsna.util.images.ValidateCode;
import com.aurora_manito.xiaomi.entity.User;
import com.aurora_manito.xiaomi.service.UserService;
import com.aurora_manito.xiaomi.service.impl.UserServiceImpl;
import com.aurora_manito.xiaomi.utils.Base64Utils;
import com.aurora_manito.xiaomi.utils.RandomUtils;
import com.aurora_manito.xiaomi.utils.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Aurora_Manito
 * @since 2020-05-27
 */
@RestController
@RequestMapping("/xiaomi/user")
public class UserController {
    @Autowired
    private UserService userService=new UserServiceImpl();
    //1.用户注册
    @PostMapping(value = "/register",produces = {"application/json;charset=UTF-8"})
    @ResponseBody //序列化--》类型转换  --》jackson ---Json
    @ModelAttribute     //设置attribute
    public ModelAndView register(User user, HttpServletRequest request, @RequestParam String repassword)
    {
        ModelAndView modelAndView =new ModelAndView("forward:/registerSuccess.jsp");
        System.out.println(user);
        if(user.getUsername().isEmpty())
        {
            request.setAttribute("registerMsg","用户名不能为空");
            //return new ModelAndView("redirect:/register.jsp");
            return new ModelAndView("forward:/register.jsp");
        }
        if(user.getPassword().isEmpty())
        {
            request.setAttribute("registerMsg","密码不能为空");
            //return new ModelAndView("redirect:/register.jsp");
            return new ModelAndView("forward:/register.jsp");
        }

        if(!user.getPassword().equals(repassword))
        {
            request.setAttribute("registerMsg","两次密码不一致");
            //return new ModelAndView("redirect:/register.jsp");
            return new ModelAndView("forward:/register.jsp");
        }
        if(user.getEmail().isEmpty())
        {
            request.setAttribute("registerMsg","邮箱不能为空");
            //return new ModelAndView("redirect:/register.jsp");
            return new ModelAndView("forward:/register.jsp");
        }
        //
        user.setFlag(0); //0未激活
        user.setRole(1);//1用户
        user.setCode(RandomUtils.createActive());
        if(userService.register(user).contains("注册成功")){
           String activeurl= "/xiaomi/user/activate?e="+ Base64Utils.encode(user.getEmail())+"&c="+Base64Utils.encode(user.getCode());
            modelAndView.addObject("activeurl",activeurl);
            System.out.println("注册成功");
            return modelAndView;
        }else {
            request.setAttribute("registerMsg","注册失败");
            //return new ModelAndView("redirect:/register.jsp");
            return new ModelAndView("forward:/register.jsp");
        }

    }
    @PostMapping("/login/auth")
    public ModelAndView login(User Checkuser, HttpSession session, String auto, HttpServletResponse response){
        /*
         *   重构：登录业务
         *   1.验证账号+密码
         *   2.登记用户 --回话跟踪
         * */
        ModelAndView loginview=new ModelAndView("forward:/login.jsp");
        if(Checkuser.getUsername().isEmpty())
        {

            //这里modelandVoew 相当于Request.setAttrbute
            loginview.addObject("msg","用户名不能为空");
            return loginview;
        }
        if(Checkuser.getPassword().isEmpty())
        {
            loginview.addObject("msg","密码不能为空");
            return loginview;
        }
        User user=userService.login(Checkuser);
        if(user==null)
        {
            loginview.addObject("msg","用户名或者密码不正确");
            return loginview;
        }else{
            //有用户
            //有没有激活
            if(user.getFlag()!=1)
            {
                loginview.addObject("msg","用户尚未激活或被禁用");
                return loginview;
            }
            //有没有权限
            if(user.getRole()!=1)
            {
                loginview.addObject("msg","用户没有权限");
                return loginview;
            }
            System.out.println("登录成功");
            session.setAttribute("user",user);
            if(auto!=null)
            {
                //处理自动登录
                String userInfo=user.getUsername()+"#"+Checkuser.getPassword();
                //创建Cookie
                Cookie cookie=new Cookie("userinfo", Base64Utils.encode(userInfo));
                cookie.setMaxAge(60*60*24*14);
                cookie.setPath("/");
//                cookie.setHttpOnly(true);
                response.addCookie(cookie);
            }
            return new ModelAndView("redirect:/index.jsp");
        }


    }

    @PostMapping(value="/checkExistsUserName",produces = {"application/json;charset=UTF-8"})
    @ResponseBody //序列化--》类型转换  --》jackson ---Json
    public ResponseMessage checkExistsUserName(@RequestParam String username){
        String result=userService.checkUserName(username);
        if(result.contains("用户名可用"))
        {
            return  ResponseMessage.success().addObject("msg",result);
        }
        return ResponseMessage.error().addObject("msg",result);
    }

    @GetMapping(value="/ValidateCode",produces = {"application/json;charset=UTF-8"})
    @ResponseBody //序列化--》类型转换  --》jackson ---Json
    public ResponseMessage ValidateCode(HttpSession session, HttpServletResponse response) throws IOException {
        //宽度，高低，验证码内容数量，干扰线
        ValidateCode validateCode=new ValidateCode(100,40,4,10);
        String code=validateCode.getCode();
        session.setAttribute("vcode",code);
        validateCode.write(response.getOutputStream());
        return ResponseMessage.success().addObject("msg","验证马成功");
    }
    @PostMapping(value="/CheckCode",produces = {"application/json;charset=UTF-8"})
    @ResponseBody //序列化--》类型转换  --》jackson ---Json
    public ResponseMessage CheckCode(@RequestParam String code,HttpSession session) {
        System.out.println(session.getAttribute("vcode").toString());
        System.out.println(code);
        System.out.println();
        if (code.equals(session.getAttribute("vcode").toString())) {
            return ResponseMessage.success().addObject("msg", "OK");
        }

        return ResponseMessage.error().addObject("msg", "ERROR");
    }

    //退出
    @GetMapping(value="/logOut",produces = {"application/json;charset=UTF-8"})
    @ResponseBody //序列化--》类型转换  --》jackson ---Json
    public ModelAndView logOut(HttpSession session,HttpServletResponse response)
    {
        //1.删除session中用户数据
        session.removeAttribute("user");
        //2.session失效
        session.invalidate();
        //3.删除Cookie
        Cookie cookie=new Cookie("userinfo","");
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);
        return new ModelAndView("redirect:/index.jsp");
    }
    @GetMapping(value="/activate",produces = {"application/json;charset=UTF-8"})
    @ResponseBody //序列化--》类型转换  --》jackson ---Json
    public ModelAndView activate(@RequestParam String e,@RequestParam String c)
    {
        String email;
        email = Base64Utils.decode(e);
        String code;
        code=Base64Utils.decode(c);
        if(!email.isEmpty()||!code.isEmpty()) {
            boolean b=userService.activate(email, code);
            if(b)
            {
                return new ModelAndView("redirect:/index.jsp");
            }
        }
        return new ModelAndView("www.baidu.com");

    }
}

